<?php

require_once( '../system/smarty.inc' );
require_once( '../system/tdao/Class_T_MON_CELL.php' );
require_once( '../system/tdao/Class_T_MON_CELL_WEEK.php' );
require_once( '../system/tdao/Class_T_PATTERN.php' );

require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );
require_once( '../system/aoki_m_plus.php' );

Class_PWD::valid_auth(AOKI_AUTH_MON_CELL, $login['staff_auth']);

//$dao     = new Class_T_MON_CELL_WEEK;
$dao_mg  = new Class_T_MON_CELL;

$errmsg     = "";
$datas      = array();
$phase      = 'input';
$aja_exits  = true;
$can_edit   = false;

if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	if( isset($_GET['ww']) && $_GET['ww'] != '' && $_GET["sort"] ){
		$matrix_cd   = $_GET['ww'];
		$dao_mg->setTableNameWeek($matrix_cd);
		if ($_GET["sort"] == '2') {
			if  ( empty( $_GET['areauser'] ) ) {
				$edit_msg = "AJAREKSコードは入力必須です";
				$aja_exits = false;
			}else {
				$aja_cd = $_GET['areauser'];
			}
		}
		
		if ($_GET["sort"] == '3') {
			$zone_cd = $_GET['zone_cd'];
			$zone_cd = trim($zone_cd);
			if  ( empty($zone_cd) ) {
				$edit_msg = "AJAREKSコードは入力必須です";
				$aja_exits = false;
			}else {
				$aja_cd = $zone_cd;
			}
		}
	}
}else {
	$matrix_cd       = $_POST["matrix_cd"];
	$aja_cd          = $_POST["aja_cd"];
}
if ( $login['staff_auth'] == 'G-2' || $login['staff_auth'] == 'G-3' ) {
	$aja_cd   = $login['autoid'];
}
if ( empty($matrix_cd) ) {
	//$forms['auth'] = 0;
	$edit_msg = "マトリクスコードは入力必須です";
}
if ( empty($aja_cd) ) {
	//
	$edit_msg = "AJAREKSコードは入力必須です";
	$aja_exits = false;
}
//-------権限チェック------------------------------------
	$formdata["matrix_cd"] = $matrix_cd;
	$formdata["aja_cd"]    = $aja_cd;
	
	$data_mg = $dao_mg->getMatrixTerm( $matrix_cd);
	
	$formdata["year4"]      = $data_mg["year4"];
	$formdata["week_seq"]   = $data_mg["week_seq"];
	$formdata["week_cd"]    = $data_mg["week_cd"];
	$formdata["flier_date"] = Class_PWD::int8_to_dateD( $data_mg["flier_date"] );
	
	$statusID               = Class_PWD::getMatrixStatues( $data_mg );
	
	$formdata["status"]     = $aoki_matrix_status[$statusID]; 
	$formdata["u_time"]     = $data_mg["upd_time"];		
	$is_final = FALSE;
	if ($aja_exits) {
		$login_auth = $login['staff_auth'];
		
		//if ( $login_auth == 'G-2' ) {
		//	$aja_cd          = $login['autoid'];
		//}
		$can_edit = FALSE;
		$edit_msg = "編集権限がありません";

		if (($login_auth == 'G-0') || ( $login_auth== 'G-1') ||  ($login_auth == 'G-2')) {
			switch ( $statusID ) {
				case AOKI_MATRIXS_DRAFT_CREATE:
				case AOKI_MATRIXS_DRAFT_MODIFY:
				case AOKI_MATRIXS_FINAL_MODIFT:
					if ( $login_auth == 'G-1' ) {
						$edit_msg = "";
						$can_edit = TRUE;
					}
					break;
					
				case AOKI_MATRIXS_DRAFT_INPUT:
				case AOKI_MATRIXS_FINAL_INPUT:
					if ( ( $login_auth == 'G-2' )  ) {
						$edit_msg = "";
						$can_edit = TRUE;
					}
					break;
					
				case AOKI_MATRIXS_FINAL_END:
					if ( $login_auth == 'G-1' ) {
						$edit_msg = "FINAL手配済みのデータです";						
						$can_edit = TRUE; 			
					}
					break;
				
				default:
					$edit_msg = "編集期限外です(ステータス：".$aoki_matrix_status[$statusID].") " ;
					break;
			}
			
			switch ( $statusID ) {
				case AOKI_MATRIXS_FINAL_INPUT:
				case AOKI_MATRIXS_FINAL_MODIFT:
				case AOKI_MATRIXS_FINAL_END:
					$is_final = TRUE;
					break;
			}
		}
		
		if ( $login_auth == 'G-0' ) {
			//$edit_msg = "ステータス：".$aoki_matrix_status[$statusID] ;
			$edit_msg = "";
			$can_edit = TRUE;
		}
		
	}
//-------権限チェック---------------end---------------------
//$is_final = FALSE;]


if ($can_edit && $aja_exits) {
	//-------------------各パラメタ―作成-------------------------------------------------------------
	$data_title     = $dao_mg->getTitle( $matrix_cd );
	require_once( '../system/cell_parametas.inc.php' );
	//-------------各パラメタ―作成完了---------------------------------------------------------------
	if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
		

		
	} else {
			
		$forms  = $_POST;
		
		$dao_mg->setTableNameWeek($forms["matrix_cd"]);
		$shopmapno = $_SESSION['SHOPMAPNO'] ;
		if( $forms['mode'] == 'input' ){
			$can_edit = true;
			//フォームデータ整形
			$values  = array();
			$vidarr  = array();
			$err     = new Class_ERROR("", "");
			$has_err = false; 
			//画面からデータの整形
			foreach ( $forms as $k => $v ) {
				if (is_array($v)) {
					foreach ( $v as $kk => $vv ) {
						$datas[$kk][$k] = $vv;
					}
				}
			}
			//print_r($datas);
			//$aja_cd  = $forms["aja_cd"] ;
			//整形完了
			unset($forms);
			$err_mes = array();
			foreach ($datas as $k => $v) {
				$shoperrmsg[$flgs["shop"]]= FALSE;
			}
			foreach ($datas as $k => $v) {
				$hasTitle = false;
				$valuesd = array();
				$line    = $k * 1 + 1;
				//通常チラシ
				$flgs = array();
				$flgs["qtype"] = "0" ;   //0  通常チラシ　1 地域１、2 地域2、3 地域3、4 地域4、5 地域5
				$flgs["wtype"] = "9" ;   //9  非例外曜日　0-6 例外曜日の番号　
				$flgs["name"]  = "通常チラシ" ;
				$flgs["shop"]    = $v["shop_name"];
				$flgs["map_no"]  = $v["mpno"];
				$flgs["isirgyu"] = $v["isirgyu"];
				
				/*
				//マップＮＯの計算
				if ($v["hirgyu"] ) {
					$flgs["map_no"] = empty($v["hirgyu"]) ? 0 : $v["hirgyu"];
					$flgs["isirgyu"] = 1;
				} else {
					$flgs["map_no"] = empty($v["rgyu"]) ? 0 : $v["rgyu"];
					$flgs["isirgyu"] = 0;
				}
				*/
				
				if ( $v["title_cd"] ) {
					$hasTitle  = true;
				}
				$pval = getPValues( $v["title_cd"], $v["pc_b2"],$v["npc_b2"], $v["smpc_b2"] ,'B2' , $flgs, $err_mes) ;
				if ( $pval ) {
					$valuesd[]    = $pval;
				}
				$pval = getPValues( $v["title_cd"], $v["pc_b3"],$v["npc_b3"], $v["smpc_b3"] ,'B3' , $flgs, $err_mes) ;
				if ( $pval ) {
					$valuesd[]    = $pval;
				}
				$pval = getPValues( $v["title_cd"], $v["pc_b4"],$v["npc_b4"],$v["smpc_b4"] , 'B4' , $flgs, $err_mes) ;
				if ( $pval ) {
					$valuesd[]    = $pval;
				}
				
				if (!checkallsize($v["title_cd"],  $v["pc_b2"],$v["npc_b2"], $v["pc_b3"],$v["npc_b3"],$v["pc_b4"],$v["npc_b4"], $flgs, $err_mes,$shoperrmsg)) {
					$has_err = true;
				} 	
				
				//例外曜日チラシ
				foreach ($data_cell_wsets as $kf => $vf) {
					$flgs["name"]  = $vf["name"];
					$flgs["wtype"] = $kf ;
					/*
					if ( $v[$vf["title_cd"]] ) {
						$shop = $flgs["shop"] ;
						if ($hasTitle) {
							$err_mes[] = "{$shop}: 通常と例外曜日のタイトル同時に入力不可です";
						}else {
							$hasTitle  = true;
						}
					}
					*/
					$shop = $flgs["shop"] ;
					
					$pval = getPValues( $v["title_cd"], $v[$vf["pc_b2"]],$v[$vf["npc_b2"]],$v[$vf["smpc_b2"]] , 'B2' ,$flgs , $err_mes ) ;
					if ( $pval ) {
						$valuesd[]    = $pval;
					}

					$pval = getPValues( $v["title_cd"], $v[$vf["pc_b3"]],$v[$vf["npc_b3"]], $v[$vf["smpc_b3"]],'B3' ,$flgs , $err_mes ) ;
					if ( $pval ) {
						$valuesd[]    = $pval;
					}
					$pval = getPValues( $v["title_cd"], $v[$vf["pc_b4"]],$v[$vf["npc_b4"]],$v[$vf["smpc_b4"]] , 'B4' ,$flgs , $err_mes) ;
					if ( $pval ) {
						$valuesd[]    = $pval;
					}
					
					if (!checkallsize($v["title_cd"],  $v[$vf["pc_b2"]],$v[$vf["npc_b2"]], $v[$vf["pc_b3"]],$v[$vf["npc_b3"]],  $v[$vf["pc_b4"]],$v[$vf["npc_b4"]], $flgs, $err_mes ,$shoperrmsg)){
						$has_err = true;
					}
				}
				/*
				//地域
				foreach ($data_cell_losets as $kf => $vf) {
					
					$flgs["name"]    = $vf["name"];
					$flgs["wtype"]   = 9 ;
					$flgs["qtype"]   = $kf ;
					$flgs["map_no"]  = empty ($v["l{$kf}"]) ? 0 : $v["l{$kf}"];
					$flgs["isirgyu"] = 0;

					$pval = getPValues( $v[$vf["title_cd"]], $v[$vf["pc_b2"]],$v[$vf["npc_b2"]], 'B2' ,$flgs , $err_mes) ;
					if ( $pval ) {
						$valuesd[]    = $pval;
					}

					$pval = getPValues( $v[$vf["title_cd"]], $v[$vf["pc_b3"]],$v[$vf["npc_b3"]], 'B3' ,$flgs , $err_mes) ;
					if ( $pval ) {
						$valuesd[]    = $pval;
					}
					$pval = getPValues( $v[$vf["title_cd"]], $v[$vf["pc_b4"]],$v[$vf["npc_b4"]], 'B4' ,$flgs , $err_mes) ;
					if ( $pval ) {
						$valuesd[]    = $pval;
					}
					if (!checkallsize($v[$vf["title_cd"]],  $v[$vf["pc_b2"]],$v[$vf["npc_b2"]], $v[$vf["pc_b3"]],$v[$vf["npc_b3"]],  $v[$vf["pc_b4"]],$v[$vf["npc_b4"]], $flgs, $err_mes)){
						$has_err = true;
					} 
				}
				*/

				//-----------
				if ( count($valuesd) > 0 ) {
					foreach ($valuesd as $dk => $dv) {
						$msg = $err->check( $dv["pnums"], array("NUM") );
						if ($msg) {
							$err_mes[] =  $msg;
						}
						$valuesd[$dk]["pattern_name"] =  $data_pattern_arr[$dv["pattern_cd"]];
						$valuesd[$dk]["title"]        =  $data_title_arr[$dv["title_cd"]];
					}
					if (count( $err_mes ) <= 0) {
						$values[$k]["matrix_cd"] = $matrix_cd;
						$values[$k]["shop_cd"]   = $v["shop_cd"];
						$values[$k]["detail"]    = $valuesd;
					} else {
						$has_err = true;
					}
				}
			}
			foreach ($shoperrmsg as $kk => $vv) {
				if (!$vv){
					if ($kk){
						$has_err = true;
						$err_mes[] = "{$kk}:  タイトルを選択した場合、 見本、チラシ部数とパターンを入力してください";
					}
				}
			}
			if (count( $err_mes ) > 0)  {
				$has_err = true;
			}

			if (!($has_err)) {
				if ($values) {	
					//print_r($values);		
					
					if ( $dao_mg->dosave( FALSE, $values, $matrix_cd, $is_final, $aja_cd ) ) {
						$has_err = true;
						$err_mes[] = '保存成功しました。';
					} else {
						$has_err = true;
						$err_mes[] = "ＤＢへ更新エラー";
					}
				} else {
					$has_err = true;
					$err_mes[] = "編集してください。";
				}
			}else {
				$has_err = true;
				$err_mes[] = "チェックエラー";
			}

		}
		if ($has_err) {
			$errmsg =implode('\r\n', $err_mes);
		
		} 
	}

}

//if( isset( $errmsg ) )  $smarty->assign('errmsg',    $errmsg);
echo '
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="Content-Script-Type" content="text/javascript" />
		<meta http-equiv="Content-Style-Type" content="text/css" />
		';
if( !empty( $errmsg ) ) { 		
	echo '<script language="javascript">
			//parent.document.getElementById("submsgid").innerHTML="'.$errmsg.'";
			//alert(parent.document.getElementById("submsgid").innerHTML ="aaa");
			alert("'.$errmsg.'");
			</script>';
}
echo '</head></html>';

/*
$smarty->assign('phase',  $phase );
$smarty->assign('menu',   $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );

if ($can_edit && $aja_exits) {
	if( isset( $formdata ) ) $smarty->assign('forms',  $formdata);
	$smarty->assign('edit_msg',   $edit_msg );
	$smarty->assign('title',      $data_title_arr );
	$smarty->assign('title_map',  $data_title_map_arr );
	
	$smarty->assign('shopmapno',  $shopmapno );
	$smarty->assign('title_week', $data_title_week_arr );
	$allpattern = array();
	foreach ( $datapattern as $k => $v) {
		$allpattern[$v["media_flg"]][$v["pattern_cd"]] = $v["pattern_name"] ; 
	}
	$smarty->assign('allpattern',      $allpattern );
	$smarty->assign('patternflags',    $aoki_pattern_flags );
	
	$smarty->assign('pattern',      $data_pattern_arr );
	$smarty->assign('pattern_nums', $data_pattern_nums );
	$smarty->assign('cell_wsets',   $data_cell_wsets );
	$smarty->assign('cell_losets',  $data_cell_losets );
	//print_r($datas);
	$smarty->assign('data', $datas);
	$smarty->display('tmoncell_updatef.html');
	
} else {
	$forms["year4"]   =  $formdata["year4"] ;
	$forms["ww"]      =  $matrix_cd;
	$forms["sort"]    =  $_GET['sort'];
	$forms["areauser"]    =  $_GET['areauser'];
	$forms["zone_cd"]    =  $_GET['zone_cd'];
	
	require_once( '../system/cell_ajareks_sort.inc.php' );
	$smarty->assign('forms', $forms);
	
	$smarty->assign('year4',  Class_M_OTHER::get_years_array());
	$smarty->assign('errmsg',  $edit_msg);
	
	$week= Class_M_OTHER::get_week_array( $forms["year4"], PLEASE_SELECT_ARR ,FALSE, TRUE);
	$smarty->assign('week', $week );
	
	$smarty->display('tmoncell_update.html');
}
*/
function getPValues($m_tile, $m_pattern, $m_pnums, $m_sample, $size , $flgs, &$terr_mes) {
	//echo "*tile：{$m_tile}*pattern：{$m_pattern}*nums{$m_pnums}*";
	$ret = NULL;
	if (  (!empty ($m_pattern) ) ||  (!empty ($m_pnums) )) {
		$hasempty = false;
		if (empty ($m_tile)) {
			$hasempty  = true;
		}
		if (empty ($m_pattern)) {
			$hasempty  = true;
		}
		if (empty ($m_pnums)) {
			$hasempty  = true;
		}
		if ( $hasempty ) {	
			$flg_name = $flgs["name"];
			$shop     = $flgs["shop"];
			$terr_mes[] = "{$shop}: [{$flg_name}] の タイトル、 チラシ部数、パターンをすべて入力してください";
			
		} else {
			$ret["title_cd"]   = $m_tile;
			$ret["qtype"]      = $flgs["qtype"];
			$ret["wtype"]      = $flgs["wtype"];
			$ret["map_no"]     = empty($flgs["map_no"]) ? 0 : $flgs["map_no"] ;
			
			$ret["isirgyu"]    = $flgs["isirgyu"];
			$ret["size"]       = $size;
			$ret["pattern_cd"] = $m_pattern;
			$ret["pnums"]      = $m_pnums;
			$ret["sample"]     = empty($m_sample) ? 0 : $m_sample ;
		}
	}
	return $ret;
}

function checkallsize($m_tile, $pb2, $npb2, $pb3, $npb3, $pb4, $npb4,$flgs, &$terr_mes,&$shoperrmsg) {
	if ( (!empty ($m_tile) ) ) {
		
		if ( empty($pb2) &&  empty($pb3) &&  empty($pb4) ) {
			//$flg_name = $flgs["name"];
			//$shop     = $flgs["shop"];
			//$terr_mes[] = "{$shop}: [{$flg_name}]  タイトルを選択した場合、 チラシ部数とパターンを入力してください";
			
			//$shoperrmsg[$shop] = "{$shop}: タイトルを選択した場合、 チラシ部数とパターンを入力してください";
			return true;
		}else {
			$shop  = $flgs["shop"];
			if ($shoperrmsg[$shop]){
				$terr_mes[] = "{$shop}: タイトルを選択した場合、 通常チラシと例外曜日を当時に入力不可";
				$shoperrmsg[$shop] = TRUE;
				return false;
			}
			$shoperrmsg[$shop] = TRUE;
		}
		$num = 0;
		if ( (!empty($npb2)) ) {
			$num = $num + 1;
		}
		if ( (!empty($npb3)) ) {
			$num = $num + 1;
		}
		if ( (!empty($npb4)) ) {
			$num = $num + 1;
		}


		if ($num >1 ) {
			$flg_name = $flgs["name"];
			$shop     = $flgs["shop"];
			$terr_mes[] = "{$shop}: [{$flg_name}] タイトルを選択した場合、 複数パターンを入力不可です";
			return false;
		}
	}else {
		$shop  = $flgs["shop"];
		$shoperrmsg[$shop] = TRUE;
	}	
	return true;
	
}

?>